// pages/search/index.js
let objectId
let app = getApp()
let content = ""
let fromID = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
      hotrecent: [{
      title: "",
      icon_url: ""
    }],
    clearHidden: true,
    searchInput: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    objectId = options.objectId ? options.objectId : ""
    fromID = options.fromID
  },

  getRecentSearch: function () {
    for (var objectId, keyWordArr = wx.getStorageSync("recentKeyword").split(","), content = [], x = 0; x < keyWordArr.length; x++) 
    if (keyWordArr[x] != "") {
      objectId = 0;
      for (var j = 0; j < content.length; j++) 
        keyWordArr[x] == content[j] && (objectId = !0)
      0 == objectId && content.push(keyWordArr[x])
    }
    wx.setStorageSync("recentKeyword", content.join(",")), this.setData({
      hotrecent: content
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getRecentSearch();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  getSearchContent: function (e) {
    content = e.detail.value;
    let clearHidden

    if (e.detail.value != '')
      clearHidden = false
    else
      clearHidden = true

    this.setData({
      searchInput: e.detail.value,
      clearHidden: clearHidden
    })
  },
  search: function () {
    var keyWord = wx.getStorageSync("recentKeyword")
    keyWord = keyWord == ""? content : keyWord + "," + content
    wx.setStorageSync("recentKeyword", keyWord)
    if (fromID == 1)
      this.unloadPrev()
    wx.redirectTo({
      url: "/pages/category/list?content=" + content + "&id=" + objectId
    });
  },
  toSearch: function (data) {
    if (fromID == 1)
      this.unloadPrev()
    wx.redirectTo({
      url: "/pages/category/list?content=" + data.target.dataset.text + "&id=" + objectId 
    });
  },

  clearSearch: function () {
    wx.clearStorageSync(), this.getRecentSearch();
  },

  /**
  * 清除搜索框内容
  */
  clear: function () {
    this.setData({
      searchInput: '',
      clearHidden: true
    })
    content = ''
  },


  /**
  * 卸载上一页
  */
  unloadPrev: function () {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    prevPage.onUnload()
  },
})